<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid #999;
        }
    </style>
</head>
<body>
    <button>发送</button>
    <button>取消</button>
    <div id="result"></div>
    <script>
        //获取button元素
        const btns = document.querySelectorAll('button');
        let x = null
        //标识变量
        let isSending = false
        //绑定事件
        btns[0].onclick = function() {
            console.log(isSending);
            if(isSending) x.abort()
            isSending = true
            console.log(isSending);
            //创建对象
            x = new XMLHttpRequest()
            //设置响应体数据的类型
            // xhr.responseType = 'json'
            //初始化 设置类型和URL
            x.open('GET','http://127.0.0.1:8000/delay')
            //设置预定义请求头
            // x.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
            //发送
            x.send();
            //事件绑定，处理服务端返回的结果,readystate是xhr对象中的属性，表示状态0 1 2 3 4
            x.onreadystatechange = function() {
               //判断（服务端返回所有的结果）
               if(x.readyState === 4){
                   isSending = false
                   if(x.status >= 200 && x.status < 300){
                        //处理结果
                       result.innerHTML = x.response
                       //或者手动转换
                    //    let data = JSON.parse(xhr.response)
                    //    result.innerHTML = data.name
                   }
               } 
            }
        };
        btns[1].onclick = function(){
            console.log(33);
            x.abort()
        }
    </script>
</body>
</html>